#! /usr/bin/env python
# coding=utf-8


pcoc_text_file = r'pt'


conv_lista = []

import os
from ete3 import PhyloTree



import argparse
import sys



parser = argparse.ArgumentParser(
    description='''书写pcoc 的 对应物种 用于之后读取使用
    conver03_give_pcoc_text.py  -i OGS_for_second_step -c con_group
    由大天才于2021年11月12日创建于浙江农业大学''')


parser.add_argument('-i',
                help='必须给定,第二步读取完成的工作路径')

parser.add_argument('-c',
                help='必须给定,趋同类群的配置文件 一行一个类 用空格空开')
args = parser.parse_args()

if not args.i or not args.c:
    parser.print_help()
    sys.exit()


infile = args.i
conv_group_file = args.c # r'con_group'


with open(conv_group_file) as fila:
	for i in fila:
		k = i.strip().split(' ')
		if k!=[] and k!=['']:
			conv_lista.append(k)


def give_tree_node(tree1,n):
	global conv_lista
	global make_lista
	
	for i in tree1.get_children():
		n = give_tree_node(i,n)
		n += 1
		tag = n-1
		#print(i)
		
		for x,y in enumerate(conv_lista):

			l = i.get_leaf_names()
			#print(l)
			t = 0
			for spe in l:
				if spe not in y:
					t = 1
					break

			if t == 0:

				make_lista[x].append(str(tag))
		
		

		


	return n
		

text = ''

for i in os.listdir(infile):
	target_file = infile+'/'+i+'/spe_tree'
	tree = PhyloTree(target_file)
	make_lista = [[] for i in conv_lista]
	n = 0
	give_tree_node(tree,n)
	# 生成text
	#print(make_lista)
	text = '/'.join([','.join(t) for t in make_lista if t !=[]])

	pcoc_text = open( infile+'/'+i+'/'+pcoc_text_file,'w')
	pcoc_text.write(text+'\n')

	#break

# 